{% extends 'base.html' %}
{% block content %}
    {{ super() }}
    {% block message_content %}{% endblock %}


    <div class="modal fade" id="detailModal" tabindex="-1">
        <div class="modal-dialog" style="max-width:1100px;">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">参数核对</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="modalContent">加载中...</div>
            </div>
        </div>
    </div>
<script>
    async function getResult(bizId, action, btnText,businessGuid) {
        const params = new URLSearchParams({
            biz_id: bizId,
            action: action,
            btnText: btnText,
            businessGuid: businessGuid
        });
        const res = await fetch(`/query_result_api?${params}`);
        const result = await res.json();
        let records = result.records;
        let html;
        if (Array.isArray(records) && records.length > 0) {
            let tableHtml = '<table class="table table-bordered"><thead><tr><th>序号</th><th>步骤名称</th><th>异常信息</th><th>状态</th><th>操作</th></tr></thead><tbody>';
            records.forEach(row => {
                tableHtml += `<tr>
                    <td style="width:15%;">${row[0]}</td>
                    <td style="width:15%;">${row[1]}</td>
                    <td style="width:40%;">${row[2]}</td>
                    <td style="width:15%;">${row[3] == 1 ? '成功' : '失败'}</td>
                    <td style="width:15%;">${
                    row[1] === '消息存储'
                        ? `<a target="_blank" href="/compare?biz_id=${bizId}&action=${action}&businessGuid=${businessGuid}">数据对比</a>`
                        : ''
                }</td>
                </tr>`;
            });
            tableHtml += '</tbody></table>';
            html = `<div class="my-content"><p>${result.sql}</p>${tableHtml}</div>`;
        } else {
            html = "无结果";
        }
        return {html, len: records.length};
    }

    async function fillingFormByParam(btn) {
        const id = btn.dataset.id;
        const action = btn.dataset.action;
        const btnText = btn.textContent;

        const paramRes = await fetch('get_' + btnText + '_param' + '?id=' + id + '&action=' + action, {
            method: 'GET',
            headers: {'Content-Type': 'application/json'}
        });
        const data = await paramRes.json();

        const htmlRes = await fetch('/static/request.html');
        const html = await htmlRes.text();

        document.getElementById('modalContent').innerHTML = html;
        document.getElementById('txt_action').value = action || '';
        document.getElementById('txt_url').value = data.url || '';
        document.getElementById('request_body').value = data.request_body || '';
        document.getElementById('txt_bizId').value = data.bizId || '';
        document.getElementById('txt_businessGuid').value = data.businessGuid || '';
        document.getElementById('execBtn').textContent = btnText || '';

        document.getElementById('execBtn').onclick = async function () {
            let action = document.getElementById('txt_action').value;
            let bizId = document.getElementById('txt_bizId').value;
            let businessGuid = document.getElementById('txt_businessGuid').value;
            let win = window.open('/static/log.html', '_blank');
            let startTime = Date.now();

            const apiRes = await fetch('/do_api?action=' + action, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    request_body: document.getElementById('request_body').value,
                    url: document.getElementById('txt_url').value,
                    auth: document.getElementById('txt_auth').value,
                    tenant_code: document.getElementById('txt_tenant').value
                })
            });
            const apiData = await apiRes.json();

            win.postMessage(`<h3>curl</h3><div class="my-content">${apiData.curl}</div>`, '*');
            win.postMessage(`<h3>response</h3><div class="my-content">${apiData.response}</div>`, '*');
            win.postMessage(`<h3>logs</h3>`, '*');

            if (JSON.parse(apiData.response).success === false) {
                win.postMessage(`<div class="alert alert-danger" role="alert">接口调用失败，请检查参数！</div>`, '*');
                return;
            }

            let {html, len} = await getResult(bizId, action, btnText,businessGuid);
            win.postMessage(JSON.stringify({type: "updateTable", html}), "*");

            if (len >= 4) {
                let cost = Date.now() - startTime;
                win.postMessage(JSON.stringify({type: "showLoading", html: "Complete，耗时：" + cost + "ms"}), "*");
                return;
            }
            let count = 0;
            let timer = setInterval(async function () {
                count++;
                let {len: newLen, html: newHtml} = await getResult(bizId, action, btnText,businessGuid);
                win.postMessage(JSON.stringify({type: "updateTable", html: newHtml}), "*");
                if (count >= 6 || newLen >= 4) {
                    clearInterval(timer);
                    let cost = Date.now() - startTime;
                    win.postMessage(JSON.stringify({type: "showLoading", html: "Complete，Cost：" + cost + "ms"}), "*");
                }
            }, 1500);
        };

        var detailModal = new bootstrap.Modal(document.getElementById('detailModal'));
        detailModal.show();
    }

    document.querySelectorAll('.btn_api').forEach(function (btn) {
        btn.addEventListener('click', function () {
            document.querySelectorAll('table tr').forEach(tr => tr.classList.remove('table-info'));
            btn.closest('tr').classList.add('table-info');
            fillingFormByParam(btn);
        });
    });
</script>
{% endblock %}